<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use fast\Http;
use other\Rsa;
use think\Db;

/**
 * 广州聚诚
 * 账户：15813329928
 * 密码：654321
 */
class MoGuTouGuangZhouJuCheng
{


//    private $tenantId='056082';
//    private $cluePoolCode='93107929';
//    private $channelCode='12845930';
//    private $sysSecret='W4mf7gnPBq5XMRdW8O107a0umPgd8pHT';
//    private $tenSecret='uQ0fGnAGmp61VtOg7Ax5p6bVTrrYVUCk';

    private $tenantId='599388';
    private $cluePoolCode='97654872';
    private $channelCode='52781292';
    private $sysSecret='W4mf7gnPBq5XMRdW8O107a0umPgd8pHT';
    private $tenSecret='HXJaafFuvny3LFuG1y5g6i7qQgk7eL58';


    public function pushClue($mapping, $clue_info, $listPush)
    {

        $apiName = '【' . $mapping['api_name'] . '】';

//        $clue_info['clue_name']='张测试';
//        $clue_info['phone']='15988888880';
//        $clue_info['ip']='192.168.1.1';

//        $this->getValidate($apiName,$clue_info); // 手机号码的撞库
        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if (!$clue_rule) {
            $errMsg = $apiName . '读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'], $errMsg, $clue_info);
            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        } else {

            foreach ($clue_rule as $v){
                $params[$v['curr']] = $clue_info[$v['orig']];
                if($v['orig'] == 'city'){
                    if (!empty($clue_info['show_city'])) {
                        if (strpos($clue_info['show_city'], '-') !== false) {
                            $city_t = explode('-', $clue_info['show_city']);
                            if (count($city_t) == 3) {
                                $showCity =$city_t[0].'-'.$city_t[1];
                            } elseif (count($city_t) == 2) {
                                $showCity =$city_t[0].'-'.$city_t[1];
                            } elseif (count($city_t) == 1) {
                                $showCity = $city_t[0];
                            }
                        }else{
                            $showCity=$clue_info['show_city'];
                        }
                        $params[$v['curr']]=$showCity;
                    }else{
                        $citys = explode('-',$clue_info[$v['orig']]);
                        $city_info = Db::name('city')->where(['type'=>2,'id'=>$citys[1]])->find();
                        $params[$v['curr']] = $city_info['name'];
                    }

                }
            }

            if(strpos($clue_info['apply_limit'], '-') !== false){
                $moneyArr=explode('-',$clue_info['apply_limit']);
                $moneyNum=count($moneyArr);
                if($moneyNum==1){
                    $MoneyStr=$moneyArr[0];
                }else{
                    $MoneyStr=$moneyArr[1];
                }
            }else{
                $MoneyStr=$clue_info['apply_limit'];
            }

            if(strpos($MoneyStr, '万') !== false){
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['loanAmount']=$MoneyStr;
            }else{
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['loanAmount']=intval($MoneyStr/10000);
            }

            if($clue_info['gender']){
                $params['sex']=$clue_info['gender'];
            }

            $params['tenantId']=$this->tenantId;
            $params['channelCode']=$this->channelCode;
            $params['cluePoolCode']=$this->cluePoolCode;

            $timestamp=time().'000';
            $randomStr=random_str(6);

            $params['randomStr']=$randomStr;
            $params['timestamp']=$timestamp;
            $params['signature']=$this->getSign2($clue_info['phone'],$timestamp,$randomStr);

//            if($params['age']==0){
//                $params['age']=mt_rand(30,50);
//            }


            $remarkStr='';
            //渠道
//            if(!empty($clue_info['push_channel'])){
//                $source=$clue_info['push_channel'];
//            }else{
//                $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
//                $source=$advInfo['show_channel'];
//                if(empty($source)){
//                    $source=get_channel_desc($clue_info['type']);
//
//                }
//            }

//            $remarkStr.=$source.'-';


            if($clue_info['pro_id']==3){
                $params['exdFields']['house']=1;
                $remarkStr.='有房-';
            }elseif ($clue_info['pro_id']==4){
               $params['exdFields']['car']=1;
                $remarkStr.='有车-';
            }elseif ($clue_info['pro_id']==6){
                $params['exdFields']['houseFund']=1;
                $remarkStr.='有公积金-';
            }else{
                $errMsg=$apiName.'线索推送商户处理失败贷款类型不符';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$params);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

            if(empty($clue_info['remark'])){
            }else{
                $remark=json_decode($clue_info['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if(strpos($kk, '城市') !== false){
                            }else{
                                $remarkArr[]=$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($clue_info['type']==1){
                                if(strpos($vv['name'], '城市') !== false){
                                }else{
                                    $remarkArr[]=$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if(strpos($vv['name'], '城市') !== false){
                                    }else{
                                        $remarkArr[]=$vv['value'];
                                    }
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr[]=$remark;
                }
                $remarkStr=$remarkStr.implode('|',$remarkArr);
            }


            $postData['param']=$params;

//            dump($postData);
            $api_url = $mapping['api_url'];


            $res_json = $this->postJson($api_url, $params);
//           dump($res_json);
            $res = json_decode($res_json, true);
//            dump($res);die;
            if (!empty($res)) {
                $res['params'] = $postData;
                if ($res['code'] != 200) {
                    $errMsg = $apiName . '线索推送商户处理失败：' . $res['msg'];
                    ClueErrorLog::record($clue_info['clue_id'], $errMsg, $res);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                    throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
                }
            } else {
                $errMsg = $apiName . '线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'], $errMsg, $postData);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
            }
            return $res;
        }
    }



//可以直接用
    public function getValidate($apiName,$clue_info)
    {
        $api_url = 'https://crm.mogutou.com/api/dz-api/clue/access/check';

        $timestamp=time().'000';
        $randomStr=random_str(6);


        $api_params=[
            'tenantId'=>$this->tenantId,
            'md5Code'=>strtolower(md5($clue_info['phone'])),
            'signature'=>$this->getSign($timestamp,$randomStr),
            'randomStr'=>$randomStr,
            'timestamp'=>$timestamp,
        ];


        $res_json = $this->postJson($api_url, $api_params);
        $res  = json_decode($res_json, true);
//        dump($api_params);
//        dump($res);
//        die;
        if(!empty($res)){
            if($res['code']!=200||$res['data']=='duplicate'){
                $res['params']=$api_params;
                $errMsg=$apiName.'CRM手机号码的撞库失败：'.$res['msg'];
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }else{
//                if($res['data']['phoneMd5Exist']){
//                    if(empty($clue_info['is_find'])&&!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city']){
//                        $clue_info['city'] = $clue_info['clue_city'];
//                        $clue_info['next_city'] = $clue_info['clue_city'];
//                        $listPush[]=$clue_info['push_id'];
//                        $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                        if($clueRes['code']!=200){
//                            $errMsg=$clueRes['msg'];
//                            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'CRM手机号码的撞库重复';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                        $isRe=Db::name('clue_err_log')->where(['type'=>2,'adv_id'=>$clue_info['adv_id'],'pro_id'=>$clue_info['pro_id'],'clue_id'=>$clue_info['id']])->find();
//                        if(empty($isRe)){
//                            Db::name('clue_err_log')->insert([
//                                'type'=>2,
//                                'clue_id'=>$clue_info['id'],
//                                'adv_id'=>$clue_info['adv_id'],
//                                'pro_id'=>$clue_info['pro_id'],
//                                'city'=>$clue_info['city'],
//                                'create_time'=>time()]);
//                        }
//                        if(empty($clue_info['is_find'])){
//                            $listPush[]=$clue_info['push_id'];
//                            $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                            if($clueRes['code']!=200){
//                                $errMsg=$clueRes['msg'];
//                                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                            }
//                        }else{
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }
//                }
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }

    private function getSign($timestamp,$randomStr){

        $str=$this->tenantId.$timestamp.$randomStr.$this->sysSecret.$this->tenSecret;
//        dump($str);
        // 生成sign
//        $signStr = $str . '&key=' . $token;
        $signstr=strtolower(md5($str));
//        dump($signstr);
        return $signstr;
    }

    private function getSign2($phoneNumber,$timestamp,$randomStr){

        $str=$this->tenantId.$phoneNumber.$timestamp.$randomStr.$this->sysSecret.$this->tenSecret;
//        dump($str);
        // 生成sign
//        $signStr = $str . '&key=' . $token;
        $signstr=strtolower(md5($str));
//        dump($signstr);
        return $signstr;
    }

    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {
        $curl = curl_init();
        $timeStamp = time().'000';

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        $params = json_encode($data, JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }

    public function postData($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            'Content-Type: application/json; charset=utf-8',
//        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }



}